package vn.com.hung.notetaker.book.components;

import java.awt.Component;
import java.awt.FontMetrics;
import java.awt.Insets;

import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.TableCellRenderer;

import vn.com.hung.notetaker.book.datamodels.BNTableModel;
import vn.com.hung.notetaker.utils.FontPool;
import vn.com.hung.notetaker.utils.StringUtils;

@SuppressWarnings("serial")
public class BNTableRenderer extends JTextArea implements TableCellRenderer {
    
    public BNTableRenderer() {
        setFont(FontPool.MEDIUM_SERIF_BOLD);
        setLineWrap(true);
        setWrapStyleWord(true);
        setMargin(new Insets(0, 2, 0, 2));
       
    }


    @Override
    public Component getTableCellRendererComponent(
        JTable jTable, Object value, boolean isSelected,
        boolean hasFocus, int row, int column) {

        FontMetrics  font =  getFontMetrics(getFont());
        String text = value.toString();
        setText(text);  
        int columnWidth = jTable.getColumnModel().getColumn(column).getWidth();
        int height_wanted = StringUtils.getStringHeight(text, font, columnWidth, jTable.getRowHeight());
        int currentHeight = jTable.getRowHeight(row);
        if (height_wanted > currentHeight)  {
         jTable.setRowHeight(row, height_wanted);
         ((BNTableModel)jTable.getModel()).setHighestCell(row, column);
        
        } else if (height_wanted < currentHeight) {
            if (((BNTableModel) jTable.getModel()).getHighestCell(row) == column) {
                   jTable.setRowHeight(row, height_wanted);
            }
        } else {
            // do not render here
            // note that Jtable.setRowHeight is very memory consuming
        }
        
        return this; 
    }
}
